package com.sq.partner.manager.common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.dao.impl.BaseDaoImpl;
import com.sq.partner.manager.util.ApplicationContextUtil;
import com.sq.partner.manager.util.LogUtil;

public class GatewayCache {
	private static Logger logger = LogUtil.getLog(GatewayCache.class);
	private static Map<String,String> cacheMap = new HashMap<String,String>();;
/**
 * 刷新缓存 需在系统初使化完成后使用
 * @return
 * @throws AppException 
 * @throws SQLException 
 */
	public static void refresh() throws AppException, SQLException{
		synchronized (cacheMap) {
			cacheMap.clear();
			DataSource ds = (DataSource)ApplicationContextUtil.getBean("dataSource");
			if(ds == null){
				throw new AppException("无法获取数据源:"+ ds);
			}
			Connection conn = null;
			Statement stmt = null;
			ResultSet rs = null;
			try{
				conn = ds.getConnection();
				stmt = conn.createStatement();
				rs = stmt.executeQuery("select config_name,config_value from t_gateway_config");
				while (rs.next()){
					cacheMap.put(rs.getString("config_name"), rs.getString("config_value"));
				}
			}finally{
				BaseDaoImpl.close(rs);
				BaseDaoImpl.close(stmt);
				BaseDaoImpl.close(conn);
			}
		}
	}
	
	public static String getCache(String cacheName){
		if(cacheMap.isEmpty()){
			try{
				refresh();
			}catch(Exception e){
				logger.error("初使化gateWay缓存失败",e);
			}
		}
		
		return cacheMap.get(cacheName);
		
	}
}
